#include "wiringPi.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define MAX_TIME 85
#define dht22PIN 6
int dht22_val[5]={0,0,0,0,0};

void dht22_read_val()
{
  uint8_t lststate=HIGH;
  uint8_t counter=0;
  uint8_t j=0,i;
  float farenheit;
  for(i=0;i<5;i++)
   dht22_val[i]=0;
  pinMode(dht22PIN,OUTPUT);
  digitalWrite(dht22PIN,LOW);
  delay(18);
  digitalWrite(dht22PIN,HIGH);
  delayMicroseconds(40);
  pinMode(dht22PIN,INPUT);
  for(i=0;i<MAX_TIME;i++)
  {
  counter=0;  
  while(digitalRead(dht22PIN)==lststate){
      counter++;
      delayMicroseconds(1);
      if(counter==255)
        break;
    }
    lststate=digitalRead(dht22PIN);
    if(counter==255)
       break;
    // top 3 transistions are ignored  
      if((i>=4)&&(i%2==0)){
      dht22_val[j/8]<<=1;
      if(counter>16)
        dht22_val[j/8]|=1;
      j++;
    }
  }
  // verify cheksum and print the verified data  
  if((j>=40)&&(dht22_val[4]==((dht22_val[0]+dht22_val[1]+dht22_val[2]+dht22_val[3])& 0xFF)))
  {
    farenheit=dht22_val[2]*9./5.+32;
    printf("Hum=%d.%d Temp=%d.%d\n",dht22_val[0],dht22_val[1],dht22_val[2],dht22_val[3],farenheit);
  }
  else
    printf("ERROR\n");
}

int main(void)
{
  if(wiringPiSetup()==-1)
    exit(1);
  dht22_read_val();
  return 0;
}

